import fetch from 'node-fetch'
import common from "../../lib/common/common.js"

export class EpicGamesPlugin extends plugin {
    constructor() {
        super({
            name: 'Epic免费游戏信息',
            dsc: '获取Epic免费游戏信息',
            event: 'message',
            priority: 50,
            rule: [
                {
                    reg: '^#?(epic|Epic|EPIC|喜加一)$',
                    fnc: 'getEpicGamesInfo'
                }
            ]
        })
    }
    async getEpicGamesInfo(e) {
        const FETCH_DATA = await fetch('https://store-site-backend-static.ak.epicgames.com/freeGamesPromotions?locale=zh-CN&country=CN&allowCountries=CN')
        const DATA_JSON = await FETCH_DATA.json()
        const ELEMENTS = DATA_JSON['data']['Catalog']['searchStore']['elements']

        const REPLY = []
        for (let i = 0; i < ELEMENTS.length; i++) {
            const GAME_NAME = ELEMENTS[i]['title'] // 游戏名
            const GAME_DESCRIPTION = ELEMENTS[i]['description'] // 游戏介绍
            const PICTRUE = ELEMENTS[i]['keyImages'][0]['url'] // 游戏图像
            const ORIGINAL_PRICE = ELEMENTS[i]['price']['totalPrice']['fmtPrice']['originalPrice'] // 原价格
            const DISCOUNT_PRICE = ELEMENTS[i]['price']['totalPrice']['fmtPrice']['discountPrice'] // 优惠后价格
            let OFFERTYPE = ELEMENTS[i]['offerType'] // 游戏类型
            if (OFFERTYPE === "BASE_GAME") { OFFERTYPE = '游戏本体' }
            const PROMOTIONS = ELEMENTS[i]['promotions']
            const PROMOTIONAL_OFFERS = PROMOTIONS ? PROMOTIONS['promotionalOffers'] : []
            const UPCOMING = []
            const CURRENT = []
            if (PROMOTIONAL_OFFERS.length === 0) {
                UPCOMING.push(
                    '即将推出\n',
                    GAME_NAME,
                    '\n介绍：', GAME_DESCRIPTION,
                    '\n原价格：', ORIGINAL_PRICE,
                    '\n折扣价格：', DISCOUNT_PRICE,
                    segment.image(PICTRUE)
                )
            } else {
                const START_DATE = (new Date((new Date(PROMOTIONS['promotionalOffers'][0]['promotionalOffers'][0]['startDate'])).getTime() + 8 * 60 * 60 * 1000)).toISOString().replace('T', ' ').replace('.000Z', '').replace('00:00:00', '')
                const END_DATE = (new Date((new Date(PROMOTIONS['promotionalOffers'][0]['promotionalOffers'][0]['endDate'])).getTime() + 8 * 60 * 60 * 1000)).toISOString().replace('T', ' ').replace('.000Z', '').replace('00:00:00', '')
                CURRENT.push(
                    '现已推出\n',
                    GAME_NAME,
                    '\n介绍：', GAME_DESCRIPTION,
                    '\n原价格：', ORIGINAL_PRICE,
                    '\n折扣价格：', DISCOUNT_PRICE,
                    '\n优惠时间：\n', START_DATE, ' - ', END_DATE,
                    segment.image(PICTRUE)
                )
            }
            REPLY.unshift(CURRENT);
            REPLY.push(UPCOMING);
        }
        return e.reply(REPLY)
    }
}